import { nextTick, onMounted, onActivated } from 'vue'

export function onMountedOrActivated(hook: () => any) {
	let mounted: boolean

	onMounted(() => {
		hook()
		nextTick(() => {
			mounted = true
		})
	})

	onActivated(() => {
		if (mounted) {
			hook()
		}
	})
}

export function stopPropagation(event: Event) {
	event.stopPropagation()
}

export function preventDefault(event: Event, isStopPropagation?: boolean) {
	if (typeof event.cancelable !== 'boolean' || event.cancelable) {
		event.preventDefault()
	}
	if (isStopPropagation) {
		stopPropagation(event)
	}
}

export function getElementInvertColor(elment: string): string {
	const el = document.querySelector(elment)
	if (el) {
		const styles = window.getComputedStyle(el)
		const channels = styles.backgroundColor.match(/\d+/g)
		const inverted_channels = channels?.map(function (ch) {
			return 255 - Number(ch)
		})
		return 'rgb(' + inverted_channels?.join(', ') + ')'
	}
	return 'rgb(0, 0, 0)'
}
